package com.xysd.express.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xysd.express.R;
import com.xysd.express.activity.AutoWebActivity;
import com.xysd.express.activity.OrderDetailsActivity;
import com.xysd.express.activity.VoiceActivity;
import com.xysd.express.activity.expressage.ExpressageActivity;
import com.xysd.express.activity.freeride.FreeRideActivity;
import com.xysd.express.activity.logistics.LogisticsActivity;
import com.xysd.express.adapter.HomeOrderAdpter;
import com.xysd.express.base.BaseFragment;
import com.xysd.express.bean.HomePageObj;
import com.xysd.express.bean.User;
import com.xysd.express.util.GlideImageLoader;
import com.xysd.express.util.JSONParser;
import com.xysd.express.util.ToastUtil;
import com.xysd.express.util.http.HttpCallBack;
import com.xysd.express.util.http.HttpUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_home)
public class HomeFragment extends BaseFragment implements View.OnClickListener {

//    @ViewInject(R.id.banner)
    private Banner banner;
//    @ViewInject(R.id.logistics_layout)
    private LinearLayout logistics_layout;//物流
//    @ViewInject(R.id.expressage_layout)
    private LinearLayout expressage_layout;//快递
//    @ViewInject(R.id.errand_layout)
    private LinearLayout freeride_layout;//顺货
//    @ViewInject(R.id.buyhelp_layout)
    private LinearLayout buyhelp_layout;//代购
    @ViewInject(R.id.order_rv)
    private RecyclerView order_rv;

    @ViewInject(R.id.message_img)
    private ImageView message_img;
    @ViewInject(R.id.voice_img)
    private ImageView voice_img;
    private ImageView noOrder_img;

    private View headerView,footerView;

    private HomePageObj.HomePageData homeData;
    HomeOrderAdpter orderAdpter;
    List<HomePageObj.HomeOrder> orderList;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return x.view().inject(this,inflater,container);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    private void initHeader() {
        message_img.setOnClickListener(this);
        voice_img.setOnClickListener(this);
        headerView=LayoutInflater.from(mActivity).inflate(R.layout.header_home,null);
        banner= (Banner) headerView.findViewById(R.id.banner);
        logistics_layout= (LinearLayout) headerView.findViewById(R.id.logistics_layout);
        expressage_layout= (LinearLayout) headerView.findViewById(R.id.expressage_layout);
        freeride_layout= (LinearLayout) headerView.findViewById(R.id.freeride_layout);
        buyhelp_layout= (LinearLayout) headerView.findViewById(R.id.buyhelp_layout);
        footerView=LayoutInflater.from(mActivity).inflate(R.layout.footer_noorder,null);
        noOrder_img= (ImageView) footerView.findViewById(R.id.noOrder_img);
    }

    private void init() {
        initHeader();
        logistics_layout.setOnClickListener(this);
        expressage_layout.setOnClickListener(this);
        freeride_layout.setOnClickListener(this);
        buyhelp_layout.setOnClickListener(this);
        orderList=new ArrayList<>();
        orderAdpter=new HomeOrderAdpter(R.layout.item_home_order_list,mActivity);
        order_rv.setLayoutManager(new LinearLayoutManager(mActivity));
        order_rv.setAdapter(orderAdpter);
        orderAdpter.addHeaderView(headerView);
        orderAdpter.addFooterView(footerView);
        orderAdpter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(mActivity, OrderDetailsActivity.class);
                intent.putExtra("id",homeData.Orders.get(position).OrderId);
                startActivity(intent);
            }
        });
        orderAdpter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(mActivity, OrderDetailsActivity.class);
                intent.putExtra("id",homeData.Orders.get(position).OrderId);
                startActivity(intent);
            }
        });
    }


    //重写fragment是否对用户可视，当可视时加载数据（解决viewpager的预加载问题）
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    private void isCanLoadData() {
        if (getUserVisibleHint()) {
            if (User.getInstance().isLogin)
                getData();
        }
    }

    private void getData() {
        HttpUtil.getHomeData(new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.i("首页",result);
                String code= JSONParser.getStringFromJsonString("Status",result);
                String msg=JSONParser.getStringFromJsonString("Msg",result);
                if ("0".equals(code)){
                    HomePageObj homePageObj=new Gson().fromJson(result,HomePageObj.class);
                    homeData=homePageObj.Data;
                    setView();

                }else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public void onFailure(String error) {
                Log.e("首页",error);
            }
        });
    }

    private List<String>banners=new ArrayList<>();
    private void setView() {
        banners.clear();
        for (HomePageObj.HomeBanner banner:homeData.Banners
             ) {
            banners.add(banner.ImageUrl);

        }
        initBanner(banners);
        orderAdpter.setNewData(homeData.Orders);
        if (homeData.Orders.size()==0){
            noOrder_img.setVisibility(View.VISIBLE);
        }else {
            noOrder_img.setVisibility(View.GONE);
        }
    }


    private void initBanner(List<String> imgUrls) {
        //https://github.com/youth5201314/banner 教程地址
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(imgUrls);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
//        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(2500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.logistics_layout:
                startAty(LogisticsActivity.class);
                break;
            case R.id.expressage_layout:
                startAty(ExpressageActivity.class);
                break;
            case R.id.freeride_layout:
//                AutoWebActivity.startWebAty(mActivity,"http://118.122.122.236:8011/demo/paotui/index.html","顺货");
                startAty(FreeRideActivity.class);
                break;
            case R.id.buyhelp_layout:
                AutoWebActivity.startWebAty(mActivity,"http://118.122.122.236:8011/demo/daigou/index.html","代购");
                break;
            case R.id.message_img:

                break;
            case R.id.voice_img:
                startAty(VoiceActivity.class);
                break;
        }
    }
}
